import { getValue } from '@/config/RedisConfig.js'
import config from '@/config/index.js'
import jwt from 'jsonwebtoken'
import fs from 'fs'
import path from 'path'

const getJWTPayload = (token) => {
  const t = token.split(' ')[1]
  if (t) {
    return jwt.verify(token.split(' ')[1], config.JWT_SECRET)
  } else {
    return null
  }
}

const checkCode = async (key, code) => {
  const redisCode = await getValue(key)
  if (redisCode !== null) {
    if (redisCode.toLowerCase() === code.toLowerCase()) {
      return true
    }
  }
  return false
}

const getStats = (path) => {
  return new Promise((resolve) => {
    fs.stat(path, (err, stats) => {
      if (err) {
        resolve(false)
      } else {
        resolve(stats)
      }
    })
  })
}

const mkdir = (dir) => {
  return new Promise((resolve) => {
    fs.mkdir(dir, (err) => (err ? resolve(false) : resolve(true)))
  })
}
// 创建文件夹
const dirExist = async (dir) => {
  const isExist = await getStats(dir)
  // 如果该路径存在且不是文件，则返回true
  if (isExist && isExist.isDirectory()) {
    return true
  } else if (isExist) {
    // 路径存在，但这是文件
    return false
  }
  // 如果该路径不存在 ,则取上级目录
  const tempDir = path.parse(dir).dir
  const status = await dirExist(tempDir)
  if (status) {
    const result = await mkdir(dir)
    return result
  } else {
    return false
  }
}

const rename = (obj, key, newkey) => {
  if (!obj[key]) {
    return
  }
  obj[newkey] = obj[key]
  delete obj[key]
  return obj
}

export { checkCode, getJWTPayload, dirExist, rename }
